package service

import (
	"duoke/context"
	"duoke/model"
	"duoke/utils/gconv"
	"duoke/utils/gtime"
	"duoke/utils/orm"
	"errors"
	"github.com/gin-gonic/gin"
	"time"
)

var Order = new(orderService)

type orderService struct{}

func (s *orderService) Create(c *gin.Context, req model.ReqOrderCreate) (*model.Order, error) {
	accountR, _ := Request.Account(c)
	info, _ := User.Info(c, "sub_mch_id")
	goodsR, _ := Request.Goods(c)
	goodsUserR, _ := Request.GoodsUser(c)
	order := new(model.Order)
	group := new(model.Order)
	if gtime.TimeStamp() > gtime.StrToTime(goodsR.StartEndTime[1]) {
		return nil, errors.New("活动已结束，感谢关注")
	}
	if gtime.TimeStamp() < gtime.StrToTime(goodsR.StartEndTime[0]) {
		return nil, errors.New("活动还未开始")
	}
	if req.GroupId > 0 {
		group, _ = s.GetById(c, req.GroupId, "")
		if group.GroupMemberNum >= group.GroupNum {
			return nil, errors.New("该团已满团，无法参与拼团")
		}
	} else {
		order.GroupMemberNum = 1
	}
	// 判断库存
	if goodsR.Stock <= 0 {
		return nil, errors.New("该商品已售罄")
	}
	// 生产订单号
	orderNo := gconv.String(goodsUserR.Id) + gconv.String(time.Now().Local().Unix())
	// 收集表单信息
	for _, v := range req.Form {
		if v.Name == "类型" {
			order.IsNewOld, _ = v.Value.(string)
		}
		if v.Name == "姓名" {
			order.Name, _ = v.Value.(string)
		}
		if v.Name == "手机号" {
			order.Phone, _ = v.Value.(string)
		}
		if v.Name == "地址" {
			order.Address, _ = v.Value.(string)
		}
	}
	order.Acid = accountR.Id
	order.UserId = goodsUserR.UserId
	order.Openid = goodsUserR.Openid
	order.Nickname = goodsUserR.Nickname
	order.Avatar = goodsUserR.Avatar
	order.GoodsId = goodsR.Id
	order.GoodsTitle = goodsR.Title
	order.GoodsPhoto = goodsR.Photo
	order.PayAmount = goodsR.OrgPrice
	order.OrderNo = orderNo
	order.Form = req.Form
	order.FromId = goodsUserR.FromId
	order.FromId2 = goodsUserR.FromId2
	order.StaffId = goodsUserR.StaffId
	order.GroupNum = goodsR.GroupNum
	order.SubMchId = info.SubMchId
	// 原价购买
	if req.BuyType == 1 {
		order.PayAmount = goodsR.OrgPrice
		order.IsHead = -1
		order.GroupNum = 0
	}
	// 团长开团
	if req.BuyType == 2 {
		order.PayAmount = goodsR.Price
		order.GroupNum = goodsR.GroupNum
		order.IsHead = 1
	}
	// 团员参团
	if req.BuyType == 3 && group.Id > 0 {
		order.HeadUserId = group.UserId
		order.GroupId = group.Id
		order.PayAmount = goodsR.Price
		order.GroupNum = group.GroupNum
		order.IsHead = 0
		// 判断时候已经购买过该团
		hasBuy, err := orm.Db.Where("acid =? AND goods_id =? AND user_id =? AND group_id =? AND pay_state =1", accountR.Id, goodsR.Id, goodsUserR.UserId, group.Id).Count(new(model.Order))
		if err != nil {
			return nil, err
		}
		if hasBuy > 0 {
			return nil, errors.New("您已参与过该团，不可重复参与")
		}
	} else {
		order.HeadUserId = goodsUserR.UserId
	}
	if order.PayAmount <= 0 {
		return nil, errors.New("支付金额为空")
	}
	affected, err := orm.Db.Insert(order)
	if err != nil {
		return nil, err
	}
	if affected == 0 {
		return nil, errors.New("创建订单失败")
	}
	// 如果是团长开团，设置订单信息
	if order.IsHead == 1 {
		order.GroupId = order.Id
		_, _ = orm.Db.ID(order.Id).MustCols("group_id").Update(order)
	}
	return order, nil
}
func (s *orderService) GetById(c *gin.Context, id int, field string) (*model.Order, error) {
	accountR, _ := Request.Account(c)
	data := new(model.Order)
	has, err := orm.Db.ID(id).Where("acid =?", accountR.Id).Cols(field).Get(data)
	if err != nil {
		return nil, err
	}
	if !has {
		return nil, errors.New("该订单不存在")
	}
	return data, nil
}
func (s *orderService) GetByOrderNo(c *gin.Context, orderNo string, field string) (*model.Order, error) {
	accountR, _ := Request.Account(c)
	data := new(model.Order)
	has, err := orm.Db.Where("acid =? AND order_no =?", accountR.Id, orderNo).Cols(field).Get(data)
	if err != nil {
		return nil, err
	}
	if !has {
		return nil, errors.New("该订单不存在")
	}
	return data, nil
}
func (s *orderService) GetByWhere(where string, field string) (*model.Order, error) {
	data := new(model.Order)
	has, err := orm.Db.Where(where).Cols(field).Desc("id").Get(data)
	if err != nil {
		return nil, err
	}
	if !has {
		return nil, errors.New("该订单不存在")
	}
	return data, nil
}

// 获取订单
func (s *orderService) List(c *gin.Context, where string, limit int, field string) ([]model.Order, error) {
	accountR, _ := Request.Account(c)
	var req model.ReqList
	//判断子账户
	query := orm.Db.Desc("id").Cols(field).Limit(limit).Where(where)
	if accountR.Role == "goods" {
		query = query.Where("goods_id IN(" + accountR.GoodsIds + ")")
	} else {
		query = query.Where("acid =?", accountR.Id)
	}
	order := make([]model.Order, 0)
	err := query.Find(&order)
	if err != nil {
		return nil, err
	}
	for i, v := range order {
		member, err := Group.Member(req, v.GroupId, true, "")
		if err != nil {
			return nil, err
		}
		order[i].Member = member
		order[i].ShareQrcodeUrl = context.Global.Domain + "/mp/qrcode/?acid=" + gconv.String(v.Acid) + "&type=share&goodsId=" + gconv.String(v.GoodsId) + "&fromId=" + gconv.String(v.UserId)
	}
	return order, nil
}

// 获取订单
func (s *orderService) Page(c *gin.Context, req model.ReqList, where string, field string) ([]model.Order, int64, error) {
	accountR, _ := Request.Account(c)
	// 分页
	offset := (req.PageNo - 1) * req.PageSize
	//判断子账户
	query := orm.Db.Desc("id").Cols(field).Limit(req.PageSize, offset).Where(where)
	if accountR.Role == "goods" {
		query = query.Where("goods_id IN(" + accountR.GoodsIds + ")")
	} else {
		query = query.Where("acid =?", accountR.Id)
	}
	list := make([]model.Order, 0)
	total, err := query.MustLogSQL().FindAndCount(&list)
	if err != nil {
		return nil, 0, err
	}
	for i, v := range list {
		member, err := Group.Member(req, v.GroupId, true, "")
		if err != nil {
			return nil, 0, err
		}
		list[i].Member = member
		list[i].ShareQrcodeUrl = context.Global.Domain + "/mp/qrcode/?acid=" + gconv.String(v.Acid) + "&type=share&goodsId=" + gconv.String(v.GoodsId) + "&fromId=" + gconv.String(v.UserId)
	}
	return list, total, nil
}

func (s *orderService) Save(c *gin.Context, req *model.Order) error {
	var err error
	if req.Id != 0 {
		_, err = orm.Db.Where("id=?", req.Id).Update(req)
	} else {
		_, err = orm.Db.Insert(req)
	}
	return err
}
